package alpiv.trucks;

class Beetle extends Thread implements Truck {
	int myDirection;
	Road myRoad, nextR;

	Beetle(Road road, int dir) {
		myDirection = dir;
		myRoad = road;
		myRoad.setTraffic(this);
	}

	public void run() {
		try {
			myRoad.block();
			System.out.println("First driving Block for "
					+ Thread.currentThread().getName() + " (" + myRoad.getX()
					+ "," + myRoad.getY() + ")");

			for (; !arrived(); drive()) {
				// force an update
				Main.roads.roadChanged();

				try {
					Thread.sleep(500);
				} catch (InterruptedException ex) {
					ex.printStackTrace();
				}
			}
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		System.out.println("The truck " + Thread.currentThread().getName()
				+ " arrived!");

	}

	void drive() {
		int steer;

		// try straight ahead
		if (myRoad.getExit(Road.nextDirection(myDirection, Road.AHEAD)) != null) {
			System.out.println("steer now is AHEAD");
			steer = Road.AHEAD;
		} else {
			// turn right
			// (Beetles can turn in place, real trucks of course
			// cannot!)
			steer = Road.RIGHT;
			System.out.println("steer now is RIGHT");

		}
		myDirection = Road.nextDirection(myDirection, steer);

		// try to move
		nextR = myRoad.getExit(myDirection);
		if (nextR != null) {
			try {
				nextR.block();
			System.out.println("Blocked next road (" + nextR.getX() + ","
					+ nextR.getY() + ") for "
					+ Thread.currentThread().getName() + " (" + myRoad.getX()
					+ "," + myRoad.getY() + ")");

			System.out.println("Moving beetle "
					+ Thread.currentThread().getName() + "from ("
					+ myRoad.getX() + "," + myRoad.getY() + ") ----> ("
					+ nextR.getX() + "," + nextR.getY() + ")");

			nextR.setTraffic(this);
			myRoad.setTraffic(null);

			myRoad = nextR;
			myRoad.setTraffic(null);
			myRoad.unblock();
			System.out.println("Unblocked myRoad for "
					+ Thread.currentThread().getName() + " (" + myRoad.getX()
					+ "," + myRoad.getY() + ")");
			myRoad.unblock();
			System.out.println("Unblocked next road for "
					+ Thread.currentThread().getName() + " (" + myRoad.getX()
					+ "," + myRoad.getY() + ")");

			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		// myRoad.unblock();
		// } catch (InterruptedException e) {
		// System.out.println("CATCHED");
	} // finally{myRoad.unblock();

	// System.out.println("Finally unblocked myRoad for " +
	// Thread.currentThread().getName() + " (" + myRoad.getX() + "," +
	// myRoad.getY() + ")");}

	boolean arrived() {
		return myRoad.getType() == Road.GOAL;
	}

	public int getDirection() {
		return myDirection;
	}

	void setDirection(int dir) {
		myDirection = dir;
	}
}
